import React, { Component } from 'react'
// import store from './store/index'
import * as types from './store/types'

import { connect } from 'react-redux'

import axios from 'axios'


class App extends Component {

  componentDidMount(){
    this.props.getBannerList()
    this.props.getProList()
  }

  render() {
    return (
      <div>
        <h1>{this.props.count}</h1>
        <button onClick={() => {
          this.props.add()
        }}>加1</button>

        <button onClick={() => {
          this.props.addNum(10)
        }}>加指定数</button>

        <button onClick={()=>{
          this.props.reduce()
        }}>减1</button>

        <button onClick={()=>{
          this.props.reduceNum(5)
        }}>减任意数</button>

        {this.props.bannerList.map((item,index)=>{
          return(<p key={index}>
            <img style={{height:150}} src={item.img} alt="" />
          </p>)
        })}

        {this.props.proList.map(item=>{
          return(<p key={item.proid}>{item.proname}</p>)
        })}

      </div>
    )
  }
}

//将全局状态中的数据添加在当前组件的 props 属性中
const mapStateToProps = (state) => {

  //return 出去的内容就是被加在 props 中的内容
  return {
    count:state.app.count,
    bannerList:state.pro.bannerList,
    proList:state.pro.proList
  }
}

//将全局状态中修改的方法添加在当前组件的 props 中
const mapDispatchToProps = (dispatch)=>{

  //return 出去的函数就是被加在 props 中的函数
  return {
    add(){
      dispatch({type:types.ADD})
    },
    addNum(value){
      dispatch({type:types.ADDNUM,payload:value})
    },
    reduce(){
      dispatch({type:types.REDUCE})
    },
    reduceNum(value){
      dispatch({type:types.REDUCENUM,payload:value})
    },
    getBannerList(){
      axios.get('/banner/list').then(res=>{
        // console.log(res.data.data);
        dispatch({type:types.CHANGE_BANNER_LIST,payload:res.data.data})
      })
    },
    getProList(){
      axios.get('/pro/list').then(res=>{
        // console.log(res.data.data);
        dispatch({type:types.CHANGE_PRO_LIST,payload:res.data.data})
      })
    }
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(App)